package spring.spring_blog.common.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.constraintvalidators.bv.NullValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import spring.spring_blog.common.utils.JwtUtil;

import static spring.spring_blog.common.constant.Constants.USER_TOKEN_HEADER_NAME;

@Component
@Slf4j
public class loginInterceptor implements HandlerInterceptor {

    /**
     * 在执行之前先把验证知否登录了
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(USER_TOKEN_HEADER_NAME);
        if (token == null || token.equals("null")) {

            response.setStatus(406);
            log.info("令牌校验没通过：{}", request.getRequestURI());
            //跳转到登录页面
            return false;
        }
        return JwtUtil.parseToken(token) != null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


}
